<?php

namespace App\Http\Controllers\Agent;

use App\Http\Controllers\Controller;
use App\Http\Resources\PaginationCollection;
use App\Http\Service\AdaPayService;
use App\Jobs\CheckHouse;
use App\Model\Agent;
use App\Model\AgentAmountLog;
use App\Model\AgentBank;
use App\Model\AgentCashLog;
use App\Model\Business;
use App\Model\CashDisabled;
use App\Model\Device;
use App\Model\Order;
use App\Model\UserAmountLog;
use App\Model\UserBank;
use App\Model\UserBlack;
use App\Model\UserCashLog;
use App\Service\AliyunSms;
use App\Service\baofu\Util\Tools;
use App\Service\BaofuPay;
use App\Utils\Result;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;

class AccountController extends Controller
{
    public function index()
    {
        $user = $this->getUser();
        $user->draw_amt = AgentCashLog::query()->where('agent_id', $user->id)
            ->where('status', '1')->sum('cash_amt');
        $bank = AgentBank::query()->where('account_id',$user->account_id)
            ->where('agent_id',$user->id)
            ->first();
        if($bank){
            return Result::success([
                'user' => $user,
                'account'=>$bank
            ]);
        }
        return Result::success([
            'user' => $user,
        ]);
    }

    public function getBankCode(Request $request)
    {
        $keyword = $request->input('keyword');
        $bankList = DB::table('bank_code')->orderBy('code')->where(function ($q) use ($keyword) {
            if ($keyword) {
                $q->where('name', 'like', "%{$keyword}%");
            }
        })->take(50)->get(['code', 'name']);

        return Result::success($bankList);
    }

    public function sendSmsCode()
    {
        $mobile = $this->getUser()->mobile;
        $service = new AliyunSms();
        $service->generate($mobile);
        return Result::success();
    }

    public function checkSmsCode(Request $request)
    {
        if ($request->input('sms_code')) {
            if (!AliyunSms::validation($this->getUser()->mobile, $request->input('sms_code'))) {
                return Result::error(401, '短信验证码不正确');
            }
            return Result::success();
        } else {
            return Result::error(401, '短信验证码不正确');
        }
    }

    public function bindBank(Request $request)
    {
        $data = $request->only([
            'card_id',
            'card_name',
            'cert_id',
            'cert_type',
            'tel_no',
            'bank_code',
            'bank_name',
            // 'prov_code',
            // 'area_code',
        ]);
        $user = $this->getUser();
        $data['agent_id'] = $user->id;
        $bfAccount = App::make(BaofuPay::class);
        $checkLogNo = md5('A'.$user->id.$data['cert_id']);
        $getInfo= $bfAccount->getBindCardInfo($checkLogNo);
//        Log::info('get--info---'.json_encode($getInfo['bindCardInfoList'][0]));
        $user->co_name = $data['card_name'];
        // 写入银行卡
        $bank = AgentBank::where('agent_id',$user->id)->first();
        if(!$bank){
            $bank = new AgentBank($data);
            if(isset($getInfo['accInfo']) && isset($getInfo['accInfo']['contractNo'])){
                $type ='change';
                $bank->account_id = $getInfo['accInfo']['contractNo'];
                $result = $bfAccount->changeCard($data,$bank->account_id);
                $bank->status = 2;
            }else{
                $type ='create';
                $result = $bfAccount->openAgent($data);
                $bank->status = 1;
            }
        }else{
            if($bank->account_id && $bank->bank_acct_type == 2 && isset($getInfo['accInfo']) && isset($getInfo['accInfo']['contractNo'])){
                $type ='change';
                $bank->account_id = $getInfo['accInfo']['contractNo'];
                $result = $bfAccount->changeCard($data,$bank->account_id);
                $bank->status = 2;
            }else{
                $type ='create';
                $result = $bfAccount->openAgent($data);
                $bank->status = 1;
            }
            $bank->fill($data);
        }
        if($result['retCode'] != 1){
            return Result::error(1001,$result['errorMsg']);
        }
        if(isset($result['result']) && isset($result['result'][0]['errorCode'])){
            $bank->result = json_encode($result);
            $bank->reason = isset($result['result'][0]['errorMsg'])?$result['result'][0]['errorMsg']:'操作繁忙';
            $bank->save();
            return Result::error(1002,$result['result'][0]['errorMsg']);
        }

        if($type == 'change'){
            $user->account_id = $result['contractNo'];
            $user->member_id = $checkLogNo;
        }
        $user->save();
        $bank->order_no = $checkLogNo ;
        $bank->agent_id = $user->id;
        $bank->bank_acct_type = 2;
        $bank->save();
        return Result::success($result);
    }

    /**解绑银行卡
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function unbindBank(Request $request)
    {


    }

    public function drawCash(Request $request)
    {
        $amount = $request->input('amount');
        $user = $this->getUser();
        if ($user->amount < $amount) {
            return Result::error(401, '提现余额不足');
        }
        // 单笔2万
        if ($amount > 20000) {
            return Result::error(401, '超出单笔限额2万元');
        }
        // 当日限额5万
        $maxAmount = AgentCashLog::query()->where('agent_id',$user->id)->where('created_at', '>', now()->toDateString() . ' 00:00:00')
                ->where('status', 'S')->sum('cash_amt') + $amount;
        if ($maxAmount > 50000) {
            return Result::error(401, '超出今日限额5万元');
        }

        $bfAccount  = app::make(BaofuPay::class);
        $drawResult['balance'] = $bfAccount->subAccount($amount,$user);
        if($drawResult['balance']['retCode'] != 1 || $drawResult['balance']['state'] != 1){
            $tel_no = '400-926-2566';
            return Result::error(401, '抱歉，提现失败了！请联系客服('.$tel_no.')');
        }
        $orderNo = Tools::getTsnOderid("TSN");
        $save = [
            'order_no' => $orderNo,
            'cash_type' =>'手动提现',
            'cash_amt' => $amount,
            'agent_id' => $user->id,
            'bank_name' => $user->bank->bank_name,
            'card_id' => $user->bank->card_id,
            'card_type' => $user->bank->bank_acct_type,
            'card_name' => $user->bank->card_name
        ];
        $cashLog = AgentCashLog::create($save);
        $drawResult['draw'] = $bfAccount->transferCashAgent($amount,$user,$orderNo);
        if($drawResult['draw']['retCode'] != 1 || $drawResult['draw']['state'] != 1){
            $bfAccount  = app::make(BaofuPay::class);
            $bfAccount->desAccount((float)$amount,$user);
            return Result::error(401, '发起取现失败请稍后重试');
        }
        // 扣余额
        $user->amount -= $amount;
        $user->save();
        // 写入账户明细
        AgentAmountLog::create([
            'agent_id' => $user->id,
            'type' => 5,
            'amount' => $amount,
            'log' => '提现支出'
        ]);
        // 写入记录
        $cashLog->error_msg = json_encode($drawResult);
        $cashLog->status = 2;
        $cashLog->save();
        return Result::success();
    }

    /**银行信息
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function bankInfo(Request $request){
        $user = $this->getUser();
        return Result::success($user->bank);
    }

    public function saveService(Request $request){
        $service = $request->input('service');
        $user = $this->getUser();
        if($user->type != 2){
            return Result::error(500,'该商户类型不支持修改设备管理费');
        }
        $user->service = $service;
        $user->save();
        return Result::success();
    }
    /**提现记录
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function cashLog(Request $request)
    {
        $page = $request->input('page', 1);
        $perPage = $request->input('limit',10);
        $start = $request->input('start');
        $end = $request->input('end');
        $query = AgentCashLog::query()->where('agent_id', $this->getUser()->id);
        if($start){
            $query->where('created_at','>=',$start);
        }
        if($end){
            $query->where('created_at','<=',$end);
        }
        $data = $query->orderByDesc('id')
            ->paginate($perPage, ['*'], 'page', $page);
        return Result::success(new PaginationCollection($data));
    }

    /**收益支出明细
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function amountLog(Request $request){
        $page = $request->input('page', 1);
        $perPage = $request->input('limit',10);
        $start = $request->input('start');
        $end = $request->input('end');
        $agentType = $request->input('agent_type');
        $query = AgentAmountLog::query()->where('agent_id', $this->getUser()->id);
        if($start){
            $query->where('created_at','>=',$start);
        }
        if($agentType){
            $query->where('agent_type',$agentType);
        }
        if($end){
            $query->where('created_at','<=',$end);
        }

        $data = $query->orderByDesc('id')
            ->paginate($perPage, ['*'], 'page', $page);
        return Result::success(new PaginationCollection($data));
    }


    /**营收折线图
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getCharts(Request $request){
        $user = $this->getUser();
        $start = $request->input('start');
        $end = $request->input('end');
        $agentArr = [$user->id];
        $childAgent = Agent::query()->where('pid',$user->id)->get(['id']);
        foreach($childAgent as $v){
            array_push($agentArr,$v['id']);
        }
        $devices = Device::query()->whereIn('agent_id',$agentArr)->pluck('id')->toArray();
        if($start && $end){
            $startDate = Carbon::parse($start,'UTC');  // 自定义起始日期
            $endDate = Carbon::parse($end,'UTC');  // 自定义结束日期
            $dates = [];
            $data = [];
            while ($startDate->lte($endDate)) {
                $nowDay = $startDate->toDateString();
                $dates[] = $nowDay;
                $data['date'][] = date('m/d', strtotime($nowDay));
                $startDate->addDay();
            }
        }else{
            $endDate = Carbon::now();  // 当前日期时间
            $startDate = $endDate->copy()->subDays(14);  // 最近十五天的起始日期
            $dates = [];
            $data = [];
            while ($startDate->lte($endDate)) {
                $nowDay =  $startDate->toDateString();
                $dates[] = $nowDay;
                $data['date'][] = date('m/d',strtotime($nowDay));
                $startDate->addDay();
            }
        }
        foreach($dates as $k => $v){
            $totalPay = Order::query()
                ->where('paid_at','>=',$v.' 00:00:00')
                ->where('paid_at','<=',$v.' 23:59:59')
                ->whereIn('device_id',$devices)
                ->where('status',3)
                ->where('recharge_status',3)
                ->where('is_draw',0)
                ->sum('pay_amt');
//                $totalFee = Order::query()
//                    ->where('paid_at','>=',$v.' 00:00:00')
//                    ->where('paid_at','<=',$v.' 23:59:59')
//                    ->whereIn('device_id',$devices)
//                    ->where('status',3)
//                    ->where('recharge_status',3)
//                    ->sum('fee');
            $totalFee =0;
            $data['list'][] =  sprintf("%.2f",$totalPay+$totalFee);
        }
        return Result::success($data);
    }

    /**收益统计
     * @param Request $request
     * @return void
     */
    public function amountProfit(Request $request)
    {
        $user = $this->getUser();
        $start = $request->input('start');
        $end = $request->input('end');
        $type = $request->input('type');
        $province = $request->input('province');
        $city = $request->input('city');
        $district = $request->input('district');
        if ($province) {
            $query = DB::table('agent_amount_log as al')
                ->join('order as o', 'al.order_id', '=', 'o.id')
                ->join('house as h', 'o.house_id', '=', 'h.id')
                ->where('h.province', $province)
                ->where('al.type',3)
                ->where('al.agent_id', $user->id);
            if ($city) {
                $query->where('h.city', $city);
            }
            if ($district) {
                $query->where('h.district', $district);
            }
            if ($start && $end) {
                $query->whereBetween('al.created_at', [$start . ' 00:00:00', $end . ' 23:59:59']);
            }
            $data['amount'] = $query->sum('amount');
        } else {
            if ($start && $end) {
                $query = AgentAmountLog::where('created_at', '>=', $start . ' 00:00:00');
                $query->where('created_at', '<=', $end . ' 23:59:59');
                $query->where('agent_id', $user->id);
                $query->where('type', 3);
                if ($type) {
                    $query->where('agent_type', $type);
                }
                $data['amount'] = $query->sum('amount');
            } else {
                $today = date('Y-m-d', time());
                $query = AgentAmountLog::where('created_at', '>=', $today . ' 00:00:00');
                $query->where('created_at', '<=', $today . ' 23:59:59');
                $query->where('agent_id', $user->id);
                $query->where('type', 3);
                if ($type) {
                    $query->where('agent_type', $type);
                }
                $data['amount'] = $query->sum('amount');
            }
        }
        return Result::success($data);
    }

    /**收益折线图
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function amountCharts(Request $request)
    {
        $user = $this->getUser();
        $start = $request->input('start');
        $end = $request->input('end');
        $type = $request->input('type');
        if ($start && $end) {
            $startDate = Carbon::parse($start);  // 自定义起始日期
            $endDate = Carbon::parse($end);  // 自定义结束日期
            $dates = [];
            $data = [];
            while ($startDate->lte($endDate)) {
                $nowDay = $startDate->toDateString();
                $dates[] = $nowDay;
                $data['date'][] = date('m/d', strtotime($nowDay));
                $startDate->addDay();
            }
        } else {
            $endDate = Carbon::now();  // 当前日期时间
            $startDate = $endDate->copy()->subDays(14);  // 最近十五天的起始日期
            $dates = [];
            $data = [];
            while ($startDate->lte($endDate)) {
                $nowDay = $startDate->toDateString();
                $dates[] = $nowDay;
                $data['date'][] = date('m/d', strtotime($nowDay));
                $startDate->addDay();
            }
        }
        $province = $request->input('province');
        $city = $request->input('city');
        $district = $request->input('district');

        foreach ($dates as $k => $v) {
            $query = DB::table('agent_amount_log as al')
                ->join('order as o', 'al.order_id', '=', 'o.id')
                ->join('house as h', 'o.house_id', '=', 'h.id')
                ->where('al.type', 3)
                ->where('al.agent_id', $user->id)
                ->where('al.created_at', '>=', $v . ' 00:00:00')
                ->where('al.created_at', '<=', $v . ' 23:59:59');
            if($province){
                $query->where('h.province', $province);
            }
            if ($city) {
                $query->where('h.city', $city);
            }
            if ($district) {
                $query->where('h.district', $district);
            }
            if ($type) {
                $query->where('al.agent_type', $type);
            }
            $data['list'][] = $query->sum('amount');
        }
        return Result::success($data);
    }

    /**统计营收金额
     * @param Request $request
     * @return mixed
     */
    public function insideProfit(Request $request){
        $user = $this->getUser();
        $start = $request->input('start');
        $end = $request->input('end');
        $agentArr = [$user->id];
        $childAgent = Agent::query()->where('pid',$user->id)->get(['id']);
        foreach($childAgent as $v){
            array_push($agentArr,$v['id']);
        }
        $devices = Device::query()->whereIn('agent_id', $agentArr)->pluck('id')->toArray();
        if($start &&  $end){
            $totalPay = Order::where('paid_at','>=',$start.' 00:00:00')
                ->where('paid_at','<=',$end.' 23:59:59')
                ->whereIn('device_id',$devices)
                ->where('status',3)
                ->where('recharge_status',3)
                ->where('is_draw',0)
                ->sum('pay_amt');

            $servicePay = AgentAmountLog::query()
                ->where('created_at','>=',$start.' 00:00:00')
                ->where('created_at','<=',$end.' 23:59:59')
                ->where('agent_type',2)
                ->where('agent_id',$user->id)
                ->sum('device_amount');


            $totalDevice = AgentAmountLog::query()
                ->where('created_at','>=',$start.' 00:00:00')
                ->where('created_at','<=',$end.' 23:59:59')
                ->where('agent_type',2)
                ->where('agent_id',$user->id)
                ->sum('amount');
//            $totalFee = Order::where('paid_at','>=',$start.' 00:00:00')
//                ->where('paid_at','<=',$end.' 23:59:59')
//                ->whereIn('device_id',$devices)
//                ->where('status',3)
//                ->where('recharge_status',3)
//                ->sum('fee');
        }else{
            $today = date('Y-m-d',time());
            $totalPay = Order::where('paid_at','>=',$today.' 00:00:00')
                ->where('paid_at','<=',$today.' 23:59:59')
                ->whereIn('device_id',$devices)
                ->where('status',3)
                ->where('recharge_status',3)
                ->where('is_draw',0)
                ->sum('pay_amt');
            $servicePay = AgentAmountLog::query()
                ->where('created_at','>=',$today.' 00:00:00')
                ->where('created_at','<=',$today.' 23:59:59')
                ->where('agent_type',2)
                ->where('agent_id',$user->id)
                ->sum('device_amount');
            $totalDevice = AgentAmountLog::query()
                ->where('created_at','>=',$today.' 00:00:00')
                ->where('created_at','<=',$today.' 23:59:59')
                ->where('agent_type',2)
                ->where('agent_id',$user->id)
                ->sum('amount');
//            $totalFee = Order::where('paid_at','>=',$today.' 00:00:00')
//                ->where('paid_at','<=',$today.' 23:59:59')
//                ->whereIn('device_id',$devices)
//                ->where('status',3)
//                ->where('recharge_status',3)
//                ->sum('fee');
        }
        $data['amount'] =  sprintf("%.2f",$totalPay);
        $data['self_service_fee'] =  sprintf("%.2f",$totalDevice);
        $data['all_service_fee'] = sprintf("%.2f",$servicePay);
        return Result::success($data);
    }
}
